﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Puzzler.Common.Exceptions;

namespace Puzzler.Common
{
    public static class XmlUtils
    {
        public static T ReadFromAttribute<T>(this XElement element, String attrName, Func<String,T> convert)
        {
            XAttribute attr = element.Attribute(attrName);
            if (attr == null)
                throw new PuzzlerIOException("Cannot find attribute '" + attrName + "' in element '" + element.Name + "'!");

            return convert(attr.Value);
        }

        public static string ReadFromAttribute(this XElement element, String attrName)
        {
            return ReadFromAttribute(element, attrName, s => s);
        }

        public static XElement ReadFromElement(this XElement element, String elementName)
        {
            XElement child = element.Element(elementName);
            if (child == null)
                throw new PuzzlerIOException("Cannot find element '" + elementName + "' in element '" + element.Name + "'!");

            return child;
        }
    }
}
